﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;

namespace CHFramework
{
    public class EventManager : Singleton<EventManager>
    {
        //消息处理委托，每一个事件ID，对应一个或多个消息处理函数
        public delegate void EventHandler(EventData evt);

        private Dictionary<int, EventHandler> m_EventHandlerDic = null;

        public EventManager()
        {
            m_EventHandlerDic = new Dictionary<int, EventHandler>();
        }

        /// <summary>
        /// 消息注册
        /// </summary>
        /// <param name="id"></param>
        /// <param name="handler"></param>
        public void RegisterEventListener(int id, EventHandler handler)
        {
            EventHandler evtHnadler = null;

            m_EventHandlerDic.TryGetValue(id, out evtHnadler);
            if (evtHnadler != null)
            {
                evtHnadler += handler;
                m_EventHandlerDic[id] = evtHnadler;
            }
            else
                m_EventHandlerDic.Add(id, handler);
            evtHnadler = null;//处理非常好
        }

        /// <summary>
        /// 消息移除
        /// </summary>
        /// <param name="id"></param>
        /// <param name="handler"></param>
        public void RemoveEventListener(int id, EventHandler handler)
        {
            EventHandler evtHandler = null;
            m_EventHandlerDic.TryGetValue(id, out evtHandler);
            if (evtHandler != null)
            {
                evtHandler -= handler;
                m_EventHandlerDic[id] = evtHandler;
            }
            else
                m_EventHandlerDic.Remove(id);
            evtHandler = null;
        }

        /// <summary>
        /// 消息派发
        /// </summary>
        /// <param name="evt"></param>
        public void EventDispatch(EventData evt)
        {
            if (evt != null && m_EventHandlerDic.ContainsKey(evt.EventID))
            {
                EventHandler evtHandler = m_EventHandlerDic[evt.EventID];
                if (evtHandler != null)
                    evtHandler(evt);
            }
        }
    }
}
